package org.me.marble;

import android.view.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.view.animation.*;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.widget.ImageView;
import android.graphics.PixelFormat;

/**
 *
 * @author tungi
 */

public class MainActivity extends Activity implements Runnable,
        View.OnClickListener,Animation.AnimationListener,OnClickListener{
    
    private int source;
    private Display display;
	private int dialogType=-1;
    private ImageView[] buttons;
    private AlphaAnimation pressed;
    private TranslateAnimation fromLeft,fromRight;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle){try{
        super.onCreate(icicle);
        //set background picture
        display=((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        getWindow().setBackgroundDrawable(new BackgroundImage(
        		this,R.drawable.background_main1,Color.BLACK,0.5,0.5).getCurrent());
        getWindow().setFormat(PixelFormat.RGBA_8888);

        //create instance of SoundManager
        SoundManager.getInstance();
        //initialize Audio Service
        SoundManager.initSounds(this);
        //load sounds
        SoundManager.loadSounds();
        
        //get saved options
        PushPopOptions.pop(this);

        setContentView(R.layout.main);

        //animations
        createAnimations();
        setAnimations();        

        }catch(Exception e){e.printStackTrace();}
    }

    @Override
    public void onResume(){
        super.onResume();    
        
        firstRun();

        //if there is an unfinished game, we need a continue button
        if(OptionsLibrary.started && OptionsLibrary.current_level>1){
        	buttons[0].setAlpha(255);
            buttons[0].setVisibility(View.VISIBLE);
            buttons[0].startAnimation(fromLeft);
        }
        else{
        	buttons[0].setAlpha(0);
        	buttons[0].setVisibility(View.INVISIBLE);
        }
        	
        buttons[1].startAnimation(fromRight);
        buttons[2].startAnimation(fromLeft);  
        buttons[3].startAnimation(fromRight);
        buttons[4].startAnimation(fromLeft);  
        
        (new Handler()).postDelayed(this, 500);
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	if(OptionsLibrary.sound)
    		SoundManager.stopSound(sounds.Main.ordinal());
    }
    
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	//realese all reference to Sound Service
    	SoundManager.cleanup();
    }

    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            PushPopOptions.push(this);
            finish();
            return true;
        }
        else
            return super.onKeyDown(keyCode,event);
    }

    public void onClick(View view){
        view.startAnimation(pressed);
        if(view.getId()==R.buttons.continueButton){
            source=R.buttons.continueButton;
        }
        else if(view.getId()==R.buttons.startButton){
            source=R.buttons.startButton;
        }
        else if(view.getId()==R.buttons.scoreButton){
            source=R.buttons.scoreButton;
        }
        else if(view.getId()==R.buttons.optionsButton){
            source=R.buttons.optionsButton;
        }
        else if(view.getId()==R.buttons.levelButton){
            source=R.buttons.levelButton;
        }
    }

    public void onAnimationStart(Animation arg0){
    }

    public void onAnimationEnd(Animation arg0){        
        if(source==R.buttons.continueButton){            
            Intent intent=new Intent(this,GameActivity.class);
            startActivity(intent);
        }
        else if(source==R.buttons.startButton){
        	if(OptionsLibrary.started && OptionsLibrary.current_level>1){
        		dialogType=1;
        		new AlertDialog.Builder(this)
        			.setMessage("	There is an unfinished game.\n" +
        					"The previously saved game will be lost.")
        			.setPositiveButton("Continue",this)
        			.setNegativeButton("Cancel",this)
        			.show();
        	}
        	else{	
	        	OptionsLibrary.setSavesToDefault();
	            Intent intent=new Intent(this,StartActivity.class);
	            startActivity(intent);
        	}
        }
        else if(source==R.buttons.scoreButton){
        	Intent intent=new Intent(this,ScoreActivity.class);
            startActivity(intent);
        }
        else if(source==R.buttons.optionsButton){
            //show options
            Intent intent=new Intent(this,OptionsActivity.class);
            startActivity(intent);
        }
        else if(source==R.buttons.levelButton){
            //show level
            Intent intent=new Intent(this,LevelSelection.class);
            startActivity(intent);
        }
    }

    public void onAnimationRepeat(Animation arg0){
    }

    public void createAnimations(){
        fromLeft=new TranslateAnimation(
                Animation.ABSOLUTE,-display.getWidth(),
                Animation.ABSOLUTE,0,
                Animation.ABSOLUTE,0,
                Animation.ABSOLUTE,0);
        fromLeft.setDuration(1000);
        fromLeft.setInterpolator(new LinearInterpolator());

        fromRight=new TranslateAnimation(
                Animation.ABSOLUTE,display.getWidth(),
                Animation.ABSOLUTE,0,
                Animation.ABSOLUTE,0,
                Animation.ABSOLUTE,0);
        fromRight.setDuration(1000);
        fromRight.setInterpolator(new LinearInterpolator());

        pressed=new AlphaAnimation(1.0f,0.3f);
        pressed.setDuration(1500);
        pressed.setInterpolator(new CycleInterpolator(2));
        pressed.setAnimationListener(this);
    }

    public void setAnimations(){
        buttons=new ImageView[5];
        
        buttons[0]=(ImageView)findViewById(R.buttons.continueButton);
        buttons[1]=(ImageView)findViewById(R.buttons.startButton);
        buttons[2]=(ImageView)findViewById(R.buttons.scoreButton);
        buttons[3]=(ImageView)findViewById(R.buttons.optionsButton);
        buttons[4]=(ImageView)findViewById(R.buttons.levelButton);

        buttons[0].setAnimation(fromLeft);
        buttons[1].setAnimation(fromRight);
        buttons[2].setAnimation(fromLeft);
        buttons[3].setAnimation(fromRight);
        buttons[4].setAnimation(fromLeft);

        buttons[0].setAnimation(pressed);
        buttons[1].setAnimation(pressed);
        buttons[2].setAnimation(pressed);
        buttons[3].setAnimation(pressed);
        buttons[4].setAnimation(pressed);
    }

    public void firstRun(){
    	SharedPreferences sd=
    		getSharedPreferences(Context.ACTIVITY_SERVICE,Context.MODE_PRIVATE);
    	boolean firstrun=sd.getBoolean("firstrun",true);
    	if(firstrun){
	    	String msg="The following controls have been selected automatically:\n\n";
	    	
    		String nav_type=getString(R.string.navtype);
    		if(nav_type.equals("dpad")){
    			msg+="\t> Dpad";
    			//no more things to do
    		}
    		else if(nav_type.equals("wheel")){
    			//nothing to do
    			msg+="\t> Trackball (not tested yet)";
    		}
    		else if(nav_type.equals("nonav")){
    			msg+="\t> On-Screen Control";
    			OptionsLibrary.onscreen=true;
    		}
    	
    		msg+="\n\nTo change settings, you can do it in the Control Settings menu.";	    	
	    	dialogType=0;
	    	
	    	new AlertDialog.Builder(this)
	    		.setMessage(msg)
	    		.setPositiveButton("Control Settings",this)
	    		.setNegativeButton("Cancel",this)
	    		.show();
    	}
    }    


	@Override
	public void onClick(DialogInterface dialog, int button) {
		if(button==DialogInterface.BUTTON_POSITIVE && dialogType==0){
			Intent intent=new Intent(this,OptionsActivity.class);
            startActivity(intent);
			dialog.dismiss();
		}
		else if(button==DialogInterface.BUTTON_POSITIVE && dialogType==1){
			OptionsLibrary.started=false;
        	OptionsLibrary.setSavesToDefault();
			Intent intent=new Intent(this,StartActivity.class);
            startActivity(intent);
		}
		else if(button==DialogInterface.BUTTON_NEGATIVE){
			dialog.dismiss();
			SharedPreferences.Editor ed=
	            getSharedPreferences(Context.ACTIVITY_SERVICE,Context.MODE_PRIVATE).edit();
	    	ed.putBoolean("firstrun",false);
	    	ed.commit();
		}
	}
	
	@Override
	public void run() {
		if(OptionsLibrary.sound){
			if(SoundManager.isLoadCompleted())
				SoundManager.playSound(sounds.Main.ordinal(),-1,1.0f);
			else
				(new Handler()).postDelayed(this, 500);
		}
	}
}
